<?php
// app/service/RabbitMQConsumer.php
namespace app\wsns\service;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use think\facade\Log;

class RabbitMQConsumer
{
    protected $connection;
    protected $channel;
    protected $config;

    public function __construct()
    {
//        $this->config = config('amqp');
//        $this->connection = new AMQPStreamConnection(
//            $this->config['host'],
//            $this->config['port'],
//            $this->config['user'],
//            $this->config['password'],
//            $this->config['vhost']
//        );
//        $this->channel = $this->connection->channel();

        try {
            $this->connection = new AMQPStreamConnection(
                '121.40.150.13',
                5672,
                'admin',
                '8bec07d4',
                '/'
            );
        }catch (\Exception $e){
            LOG::INFO( '异常了');
            LOG::INFO( json_encode($e));
            LOG::INFO( $e);
        }

        $this->channel = $this->connection->channel();
    }

    public function consume($queueName, $callback)
    {
        $this->channel->queue_declare($queueName, false, true, false, false);

        echo "消费组件等待消息...\n";

        $this->channel->basic_consume($queueName, '', false, false, false, false, function ($msg) use ($callback) {
            echo "消费组件收到消息: " . $msg->body . "\n";
            // 执行回调处理
            $callback($msg->body);
            //执行cmd的方法
            // 手动确认消息
            $msg->ack();
        });

        while ($this->channel->is_consuming()) {
            $this->channel->wait();
        }
    }

    public function close()
    {
        $this->channel->close();
        $this->connection->close();
    }
}